package com.admxj.mybatis.demo.plugin;


import org.apache.ibatis.executor.statement.PreparedStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.ResultHandler;

import java.sql.Statement;
import java.util.Properties;

/**
 * @author admxj
 * @version Id: MyPlugin, v 0.1 2020/6/5 12:24 上午 admxj Exp $
 */
@Intercepts(value = {
  @Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}),
  @Signature(type = StatementHandler.class, method = "parameterize", args = {Statement.class})
})
public class MyPlugin implements Interceptor {

  @Override
  public Object intercept(Invocation invocation) throws Throwable {
    System.out.println("MyPlugin interceptor : " + invocation.getMethod());
    MetaObject metaObject = SystemMetaObject.forObject(invocation.getTarget());
    Object value = metaObject.getValue("parameterHandler.parameterObject");
    System.out.println("sql 参数: " + value);

    Object proceed = invocation.proceed();

    return proceed;
  }

  @Override
  public Object plugin(Object target) {
    System.out.println("MyPlugin 包装: " + target.getClass());
    Object wrap = Plugin.wrap(target, this);

    return wrap;
  }


  @Override
  public void setProperties(Properties properties) {
    System.out.print("插件配置");
    System.out.println(properties);
  }
}
